import { assetManager, color, ImageAsset, Size, Sprite, SpriteFrame, utils, v2, Vec2 } from "cc";
import { Handler } from "./event/Handler";

/**
 * 队列
 */
export class Queue<T> {

    private elements: Array<T>;
    private _size: number | undefined;

    public constructor(capacity?: number) {
        this.elements = new Array<T>();
        this._size = capacity;
    }

    public push(o: T) {
        if (o == null) {
            return false;
        }
        //如果传递了size参数就设置了队列的大小
        if (this._size != undefined && !isNaN(this._size)) {
            if (this.elements.length == this._size) {
                this.pop();
            }
        }
        this.elements.unshift(o);
        return true;
    }

    public pop(): T {
        return this.elements.pop();
    }

    public size(): number {
        return this.elements.length;
    }

    public empty(): boolean {
        return this.size() == 0;
    }

    public clear() {
        delete this.elements;
        this.elements = new Array<T>();
    }
}

/**
 * 栈
 */
export class Stack<T>{
    private items = null;
    constructor() {
        this.items = new Array<T>();
    }
    push(data: T): void {
        this.items.push(data);
    }
    pop(): T {
        return this.items.pop();
    }
    peek(): T {
        return this.items[this.items.length - 1];
    }
    isEmpty(): boolean {
        return this.items.length === 0;
    }
    size(): number {
        return this.items.length;
    }
    clear(): void {
        this.items = new Array<T>();
    }
    print(): void {
        console.log(this.items);
    }
}

export abstract class IFMStack {
    abstract IsEnable: boolean;
    abstract curFS: IFStack;
    abstract enable();
    abstract disable();
    abstract push(fs: IFStack);
    abstract pop();
    abstract update();
    abstract popWith(fs: IFStack);
    abstract popWithMe(fs: IFStack);
    abstract popAll();
    abstract find(fs: IFStack);
}

export abstract class IFStack {
    abstract enter(fsm: IFMStack);
    abstract leave(fsm: IFMStack);
    abstract update(fsm: IFMStack);
    abstract enterFront(fsm: IFMStack);
    abstract enterBack(fsm: IFMStack);
}

/**
 * 基于栈实现的有限状态机
 */
export class FSMStack extends IFMStack {
    public IsEnable: boolean;

    public get size() {
        return this.stackState.size();
    }

    public get curFS() {
        if (this.stackState.size() < 1) {
            return null;
        }
        return this.stackState.peek();
    }

    private stackState: Stack<IFStack> = new Stack<IFStack>();

    public enable() {
        this.IsEnable = true;
    }

    public disable() {
        this.IsEnable = false;
    }

    public push(fs: IFStack) {
        if (null != this.curFS) {
            this.curFS.enterBack(this);
        }

        this.stackState.push(fs);

        fs.enter(this);
    }

    public pop() {
        if (null != this.curFS) {
            this.curFS.leave(this);
            this.stackState.pop();
        }

        if (null != this.curFS) {
            this.curFS.enterFront(this);
        }
    }

    public update() {
        if (!this.IsEnable) {
            return;
        }

        if (null != this.curFS) {
            this.curFS.update(this);
        }
    }

    public popWith(fs: IFStack) {
        while (fs != this.curFS) {
            this.pop();

            if (null == this.curFS) {
                break;
            }
        }
    }
    public popWithMe(fs: IFStack) {
        this.popWith(fs);

        if (this.curFS == fs) {
            this.pop();
        }

    }
    public popAll() {
        while (null != this.curFS) {
            this.pop();
        }
    }
    public find() {

    }
}

/**
 * 集合
 */
export interface Set<T> {
    add(t: T);
    remove(t: T);
    indexOf(t: T): number;
    size(): number;
    clear();
    toArray(): T[];
}

export class ArraySet<T> implements Set<T>{
    private arr: Array<T> = [];

    public add(t: T) {
        this.indexOf(t) < 0 && this.arr.push(t);
    }

    public remove(t: T) {
        var i = this.indexOf(t);
        if (i >= 0) {
            delete this.arr[i];
        }
    }

    public indexOf(t: T): number {
        return this.arr.indexOf(t);
    }

    public size(): number {
        return Object.keys(this.arr).length;
    }

    public clear() {
        delete this.arr;
        this.arr = [];
    }

    public toArray(): T[] {
        var arr = new Array<T>();
        for (var i = 0; i < this.arr.length; i++) {
            this.arr[i] && arr.push(this.arr[i]);
        }
        return arr;
    }
}

/**
 * 链表
 */
class Node<T>{
    public data: T;
    public next: Node<T>;
    constructor(data: T) {
        this.data = data;
        this.next = null;
    }
}

export class LinkList<T>{
    private head: Node<T>;
    private length: number = 0;
    private tail: Node<T>;
    constructor() {
        this.head = null;
        this.tail = null;
    }

    append(data: T): boolean {
        let new_node = new Node(data);
        if (this.head == null) {
            this.head = new_node
            this.tail = new_node;
        } else {
            this.tail.next = new_node;
            this.tail = this.tail.next;
        }
        this.length++;
        return true;
    }

    len(): number {
        return this.length;
    }

    insert(index: number, data: T): boolean {
        if (index == this.length) {
            this.length++;
            return this.append(data);
        }
        else {

            let insert_index = 0;
            let cur_node = this.head;

            if (insert_index == index) {
                let new_node = new Node(data);
                new_node.next = cur_node;
                this.head = new_node;
            }
            else {
                while (insert_index < index) {
                    cur_node = cur_node.next;
                    insert_index++;
                }
                let next_node = cur_node.next;
                let new_node = new Node(data);
                cur_node.next = new_node;
                cur_node.next.next = next_node;
            }

        }
        this.length++;
        return true;
    }

    remove(index): Node<T> {
        if (index < 0 || index >= this.length) {
            return null;
        }
        else {
            let del_node = null;
            if (index == 0) {
                del_node = this.head;
                if (this.length > 1)
                    this.head = this.head.next;
            }
            else {
                let del_index = 0;
                let pre_node = null;
                let cur_node = this.head;
                while (del_index < index) {
                    del_index++;
                    cur_node = cur_node.next;
                }
                pre_node = cur_node;
                cur_node = cur_node.next;
                pre_node.next = cur_node;
                //如果删除的是尾节点
                if (cur_node == null) {
                    this.tail = pre_node;
                }
            }
            this.length--;
            return del_node;
        }
    }

    get(index): Node<T> {
        if (index < 0 || index > this.length) {
            return null;
        }
        let node_index = 0;
        let cur_node = this.head;
        while (node_index < index) {
            node_index++;
            cur_node = cur_node.next;
        }
        return cur_node;
    }

    print(): void {
        let cur = this.head;
        while (cur != null) {
            console.log(cur.data);
            cur = cur.next;
        }
    }

}

export class Bit {
    public static has(bit: number, pow: number) {
        return ((bit & Math.pow(2, pow)) >> pow) > 0;
    }

    public static set(bit: number, pow: number): number {
        return bit |= Math.pow(2, pow);
    }
}

export class GetClassName {
    public static Get(A) {
        let constructorString: string = A.toString();
        console.log("constructorString", constructorString);
        let className: string = constructorString.match(/\w+/g)[1];
        return className
    }
}

export class Utitls {
    // 服务器的时区
    static serverTimeZone: number = 0;

    static RandomInt(max) {
        return Math.ceil(Math.random() * Math.floor(max));
    }

    /** 
     * 产生随机整数，包含下限值，包括上限值 
     * @param {Number} lower 下限 
     * @param {Number} upper 上限 
     * @return {Number} 返回在下限到上限之间的一个随机整数 
     */
    static Random(lower, upper) {
        return Math.floor(Math.random() * (upper - lower + 1)) + lower;
    };

    /** 
     * 通过权重取值 
     * @param {Array} weightArr 权重数组 
     * @return {Number} 返回下标
     */
    static GetIndexByWeight(weightArr) {
        let dIndex = 0, curRate = 0, totalRate = 0;

        // 求总权重
        for (let index = 0; index < weightArr.length; index++) {
            totalRate = totalRate + weightArr[index];
        }

        let rate = this.Random(1, totalRate);
        // 确定该随机值在哪个区间
        for (let index = 0; index < weightArr.length; index++) {
            let pro = weightArr[index];

            if (rate > curRate && rate <= (curRate + pro)) {
                dIndex = index;
                break;
            }

            curRate += pro;
        }

        return dIndex;
    }

    /**
     * 随机分组(可以重复)
     * @param num 分组数目
     * @param up 区间上限
     * @param lower 区间下限
     * 
     */
    static RandomGroup(num, up, lower) {
        let array = [];
        for (let index = 0; index < num; index++) {
            let v = this.Random(up, lower);
            array.push(v);
        }
        return array;
    }

    /**
     * 根据节点将锚点转换为原点
     * @param node 节点
     * @param pos 坐标
     */
    static NodePositionConversion(size: Size, pos: Vec2) {
        let v2 = new Vec2();
        v2.x = size.width / 2 - size.width + pos.x
        v2.y = 0 + pos.y
        return v2
    }

    /**
     * 获取节点原点
     * @param node 节点
     */
    static GetOriginPos(size: Size) {
        let v2 = new Vec2();
        v2.x = size.width / 2 - size.width
        v2.y = 0
        return v2
    }

    /**
     * 获取当前时间戳，毫秒
     */
    static Now() {
        var now = new Date;
        var utc_timestamp = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),
            now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
        utc_timestamp + this.serverTimeZone * 3600;
        return utc_timestamp;
    }

    /**
     * 获取当前时区
     */
    static GetTimeZone() {
        return new Date().getTimezoneOffset() / 60;
    }

    /**
     * 获取当前时间戳，秒
     */
    static NowSec() {
        return new Date().getTime() / 1000;
    }


    /** 
    * 对日期进行格式化， 和C#大致一致 默认yyyy-MM-dd HH:mm:ss
    * 可不带参数 一个日期参数 或一个格式化参数
    * @param date 要格式化的日期 
    * @param format 进行格式化的模式字符串
    *     支持的模式字母有： 
    *     y:年, 
    *     M:年中的月份(1-12), 
    *     d:月份中的天(1-31), 
    *     H:小时(0-23), 
    *     h:小时(0-11), 
    *     m:分(0-59), 
    *     s:秒(0-59), 
    *     f:毫秒(0-999),
    *     q:季度(1-4)
    * @return String
    * @author adswads@gmail.com
    */
    static DateFormat(date?: any, format?: string): string {
        //无参数
        if (date == undefined && format == undefined) {
            date = new Date();
            format = "yyyy-MM-dd HH:mm:ss";
        }
        //无日期
        else if (typeof (date) == "string") {
            format = date;
            date = new Date();
        }
        //无格式化参数
        else if (format === undefined) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        else { }
        //没有分隔符的特殊处理

        var map = {
            "y": date.getFullYear() + "",//年份
            "M": date.getMonth() + 1 + "", //月份 
            "d": date.getDate() + "", //日 
            "H": date.getHours(), //小时 24
            "m": date.getMinutes() + "", //分 
            "s": date.getSeconds() + "", //秒 
            "q": Math.floor((date.getMonth() + 3) / 3) + "", //季度 
            "f": date.getMilliseconds() + "" //毫秒 
        };
        //小时 12
        if (map["H"] > 12) { map["h"] = map["H"] - 12 + ""; }
        else { map["h"] = map["H"] + ""; }
        map["H"] += "";

        var reg = "yMdHhmsqf";
        var all = "", str = "";
        for (var i = 0, n = 0; i < reg.length; i++) {
            n = format.indexOf(reg[i]);
            if (n < 0) { continue; }
            all = "";
            for (; n < format.length; n++) {
                if (format[n] != reg[i]) {
                    break;
                }
                all += reg[i];
            }
            if (all.length > 0) {
                if (all.length == map[reg[i]].length) {
                    str = map[reg[i]];
                }
                else if (all.length > map[reg[i]].length) {
                    if (reg[i] == "f") {
                        str = map[reg[i]] + this.charString("0", all.length - map[reg[i]].length);
                    }
                    else {
                        str = this.charString("0", all.length - map[reg[i]].length) + map[reg[i]];
                    }
                }
                else {
                    switch (reg[i]) {
                        case "y": str = map[reg[i]].substr(map[reg[i]].length - all.length); break;
                        case "f": str = map[reg[i]].substr(0, all.length); break;
                        default: str = map[reg[i]]; break;
                    }
                }
                format = format.replace(all, str);
            }
        }
        return format;
    }

    /** 
* 对日期进行格式化， 和C#大致一致 默认yyyy-MM-dd HH:mm:ss
* 可不带参数 一个日期参数 或一个格式化参数
* @param date 要格式化的日期 
* @param format 进行格式化的模式字符串
*     支持的模式字母有： 
*     y:年, 
*     M:年中的月份(1-12), 
*     d:月份中的天(1-31), 
*     H:小时(0-23), 
*     h:小时(0-11), 
*     m:分(0-59), 
*     s:秒(0-59), 
*     f:毫秒(0-999),
*     q:季度(1-4)
* @return String
* @author adswads@gmail.com
*/
    static TimeFormat(time?: any, format?: string): string {

        if (format === undefined) {
            format = "hh:mm:ss";
        }

        let h = Math.floor(time / (60 * 60));
        let m = Math.floor((time - h * 60 * 60) / 60);
        let s = Math.floor(time - h * 60 * 60 - m * 60);
        var map = {
            "h": h + "", //小时 24
            "m": m + "", //分 
            "s": s + "", //秒 
        };

        var reg = "hms";
        var all = "", str = "";
        for (var i = 0, n = 0; i < reg.length; i++) {
            n = format.indexOf(reg[i]);
            if (n < 0) { continue; }
            all = "";
            for (; n < format.length; n++) {
                if (format[n] != reg[i]) {
                    break;
                }
                all += reg[i];
            }
            if (all.length > 0) {
                if (all.length == map[reg[i]].length) {
                    str = map[reg[i]];
                }
                else if (all.length > map[reg[i]].length) {
                    if (reg[i] == "f") {
                        str = map[reg[i]] + this.charString("0", all.length - map[reg[i]].length);
                    }
                    else {
                        str = this.charString("0", all.length - map[reg[i]].length) + map[reg[i]];
                    }
                }
                else {
                    switch (reg[i]) {
                        case "y": str = map[reg[i]].substr(map[reg[i]].length - all.length); break;
                        case "f": str = map[reg[i]].substr(0, all.length); break;
                        default: str = map[reg[i]]; break;
                    }
                }
                format = format.replace(all, str);
            }
        }
        return format;
    }

    /**
    * 返回字符串 为n个char构成
    * @param char 重复的字符
    * @param count 次数
    * @return String
    * @author adswads@gmail.com
    */
    static charString(char: string, count: number): string {
        var str: string = "";
        while (count--) {
            str += char;
        }
        return str;
    }

    /** 
     * 缩进显示数字 
     * @param {Number} value 要缩减的数值 
     * @param {Number} indentValue 缩进阀值，当value大于该值时就会缩进 
     * @param {String} unit 单位，当value缩进后，会加上该单位 
     * @return {String} 返回缩进后值的字符串 
     */
    static indentNum(value, indentValue?, unit?): string {
        indentValue = indentValue || 1000
        unit = unit || "K"
        if (value <= indentValue) {
            return value
        }

        if (value >= 1000000 && value < 1000000000) {
            indentValue = 1000000;
            unit = 'M';
        } else if (value >= 1000000000) {
            indentValue = 1000000000;
            unit = 'B';
        }

        let v = (value / indentValue).toFixed(1);
        return v + unit;


    }

    /**
     * 16进制颜色改为rgb
     * @param hexColor string16进制颜色 例 #ffffff
     */
    static hex2color(hexColor) {
        const hex = hexColor.replace(/^#?/, "0x");
        const c = parseInt(hex);
        const r = c >> 16;
        const g = (65280 & c) >> 8;
        const b = 255 & c;
        return color(r, g, b, 255);
    };

    /**
     * 节点的相对坐标转成世界坐标
     * @param node 节点
     */
    static GetWorldPostation(node) {
        if (node != null) {
            return node.parent != null ? node.parent.convertToWorldSpaceAR(node.position) : node.position;
        }
        return null;
    }

    static Sleep(time: number): Promise<void> {
        return new Promise<void>((resolve, reject) => { setTimeout(() => resolve(), time) });
    };

    /**
     * 创建贝塞尔曲线
     * @param t 时间
     * @param startPoint 开始坐标
     * @param endPoint 结束坐标
     * @param height 高度
     * @param angle 角度
     */
    static createBezier(t, startPoint, endPoint, height, angle) {
        // 把角度转换为弧度
        let radian = angle * 3.14159 / 180;
        // 第一个控制点为抛物线左半弧的中点
        let q1x = startPoint.x + (endPoint.x - startPoint.x) / 4;
        // let q1 = cc.v2(q1x, height + startPoint.y );
        let q3 = v2(q1x, height + startPoint.y + Math.cos(radian) * Math.abs(q1x));
        // 第二个控制点为整个抛物线的中点
        let q2x = startPoint.x + (endPoint.x - startPoint.x) / 2;
        // let q2 = cc.v2(q2x, height + startPoint.y);
        let q4 = v2(q2x, height + startPoint.y + Math.cos(radian) * Math.abs(q2x));
        // 曲线配置
        return bezierTo(t, [q3, q4, endPoint]);
    }

    static generateUUID() {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now(); //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    }

    static Log(logInfo) {
        if (window["JsAgent"]) {
            window["JsAgent"].log("time=" + Utitls.NowSec() + " loginfo =" + logInfo);
        }
        else {
            console.log("time=" + Utitls.NowSec() + " loginfo =" + logInfo);
        }
    }

    public static isEmpty(str: string): boolean {
        if (str == undefined || str == null) {
            return true;
        }
        if (typeof (str) != "string") {
            return true;
        }
        return str.replace(" ", "") == "";
    }

    /**
 * 时间戳格式化工具
 * @param timestamp 时间戳（毫秒）
 * @param format 格式模板，如 "YYYY-MM-DD HH:mm:ss"
 * @returns 格式化后的字符串
 */
    public static FormatTimestamp(
        timestamp: number,
        format: string = "YYYY年MM月DD日 HH:mm:ss"
    ): string {
        const date = new Date(timestamp);

        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString();
        const day = date.getDate().toString();
        const hours = date.getHours().toString();
        const minutes = date.getMinutes().toString();
        const seconds = date.getSeconds().toString();
        // hours = Utitls.zeroFill(parseInt(hours), 2).toString();
        return format
            .replace('YYYY', year.toString())
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', Utitls.zeroFill(parseInt(hours), 2).toString())
            .replace('mm', Utitls.zeroFill(parseInt(minutes), 2).toString())
            .replace('ss', Utitls.zeroFill(parseInt(seconds), 2).toString());
    }

    /**
 * 将时间戳转换为天、时、分、秒格式
 * @param timestamp 时间戳（默认单位：毫秒）
 * @param isSeconds 是否传入的是秒级时间戳（如 Unix 时间戳）
 * @returns { days: number; hours: number; minutes: number; seconds: number }
 */
    public static TimestampToDHMS(
        timestamp: number,
        isSeconds: boolean = false
    ): { days: number; hours: number; minutes: number; seconds: number } {
        // 统一转换为毫秒处理
        let totalMilliseconds = isSeconds ? timestamp * 1000 : timestamp;
        if (totalMilliseconds < 0) totalMilliseconds = 0;

        const totalSeconds = Math.floor(totalMilliseconds / 1000);
        const days = Math.floor(totalSeconds / (3600 * 24));
        const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const seconds = totalSeconds % 60;

        return { days, hours, minutes, seconds };
    }

    /**
     * 格式化输出为字符串（如 "3天 12:30:15"）
     * @param dhm 分解后的时间对象
     * @param showDays 是否显示天数（若为 false，天数会合并到小时中）
     * @param separator 分隔符（默认 ":"）
     * @returns 格式化后的字符串
     */
    public static FormatDHMS(
        dhm: { days: number; hours: number; minutes: number; seconds: number },
        showDays: boolean = true,
        separator: string = ":"
    ): string {
        let timeStr = "";
        if (showDays && dhm.days > 0) {
            timeStr += `${dhm.days}天 `;
        }

        // 若不显示天数，将天数合并到小时中
        const finalHours = showDays ? dhm.hours : dhm.days * 24 + dhm.hours;

        // 补零处理（如 5 → "05"）
        const pad = (num: number) => num.toString();
        timeStr += `${pad(finalHours)}${separator}${pad(dhm.minutes)}${separator}${pad(dhm.seconds)}`;

        return timeStr;
    }

    public static FormatDHMSToString(
        dhm: { days: number; hours: number; minutes: number; seconds: number },
        showDays: boolean = true,
        separator: string = ":"
    ): string {
        let timeStr = "";
        if (showDays && dhm.days > 0) {
            timeStr += `${dhm.days}天 `;
        }

        // 若不显示天数，将天数合并到小时中
        const finalHours = showDays ? dhm.hours : dhm.days * 24 + dhm.hours;

        // 补零处理（如 5 → "05"）
        // const pad = (num: number) => num.toString();
        // timeStr += `${pad(finalHours)}${separator}${pad(dhm.minutes)}${separator}${pad(dhm.seconds)}`;
        if (finalHours <= 0 && dhm.seconds <= 0 && dhm.minutes > 0) {
            timeStr = timeStr + dhm.minutes + "分种";
        }
        else {
            if (finalHours > 0) {
                timeStr = finalHours + "小时";
            }
            if (dhm.minutes > 0) {
                timeStr = timeStr + dhm.minutes + "分";
            }
            if (dhm.seconds > 0) {
                timeStr = timeStr + dhm.seconds + "秒";
            }
        }
        return timeStr;
    }

    public static FormatDHMToString(
        dhm: { days: number; hours: number; minutes: number; seconds: number },
        showDays: boolean = true,
    ): string {
        let timeStr = "";
        if (showDays && dhm.days > 0) {
            timeStr += `${dhm.days}天 `;
        }
        const finalHours = showDays ? dhm.hours : dhm.days * 24 + dhm.hours;
        if (finalHours <= 0 && dhm.seconds <= 0 && dhm.minutes > 0) {
            timeStr = timeStr + dhm.minutes + "分种";
        }
        else {
            if (finalHours > 0) {
                timeStr = finalHours + "小时";
            }
            if (dhm.minutes > 0) {
                timeStr = timeStr + dhm.minutes + "分";
            }
            if (dhm.seconds > 0) {
                timeStr = timeStr + dhm.seconds + "秒";
            }
        }
        return timeStr;
    }

    public static FormatDHMSTo2(
        dhm: { days: number; hours: number; minutes: number; seconds: number },
        separator: string = ":"
    ): string {
        let timeStr = "";
        let finalHours = dhm.hours;
        if (dhm.days > 0) {
            finalHours = dhm.days * 24 + dhm.hours;
        }
        timeStr += `${Utitls.zeroFill(finalHours, 2)}${separator}${Utitls.zeroFill(dhm.minutes, 2)}${separator}${Utitls.zeroFill(dhm.seconds, 2)}`;

        return timeStr;
    }

    public static zeroFill(num: number, len: number){
        let count = num.toString().length - len;
        if(count >= 0){
            return num;
        }
    
        let arr = new Array(-count + 1);
        return arr.join("0") + num;
    }    

    
    /**
     * 深拷贝
     * @param target 目标
     */
     public static deepCopy(target: any): any {
        if (target == null || typeof target !== 'object') {
            return target;
        }
        let result = null;
        if (target instanceof Date) {
            result = new Date();
            result.setTime(target.getTime());
            return result;
        }

        if (target instanceof Array) {
            result = [];
            for (let i = 0, length = target.length; i < length; i++) {
                result[i] = this.deepCopy(target[i]);
            }
            return result;
        }

        if (target instanceof Object) {
            result = {};
            for (const key in target) {
                if (target.hasOwnProperty(key)) {
                    result[key] = this.deepCopy(target[key]);
                }
            }
            return result;
        }
        console.warn(`不支持的类型：${result}`);
    }

    public static LoadHeadImage(head, url: string, handle:Handler = null) {
        let sprite = head.getComponent(Sprite);
        // // 不带有后缀的，必须指证文件类型
        // assetManager.loadRemote<ImageAsset>(url, { ext: '.png' }, (err, imageAsset) => {
        //     const spriteFrame = new SpriteFrame();
        //     const texture = new Texture2D();
        //     texture.image = imageAsset;
        //     spriteFrame.texture = texture;
        //     sprite.spriteFrame = spriteFrame;
        // });

        // 带有后缀的
        assetManager.loadRemote<ImageAsset>(url, (err, imageAsset) => {
            if (err) {
                return console.error("ImageAsset loadRemote failed:" + err.message);
            }
            let spriteFrame = SpriteFrame.createWithImage(imageAsset);
            sprite.spriteFrame = spriteFrame;
            if (handle) {
                handle.run();
            }
        });
    }

    public static longToSimpleNumber(long) {
        // return long.low + long.high * 0x100000000; 
        const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; // 9007199254740991
        const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER; // -9007199254740991
        // 计算 64 位整数值
        const value = long.unsigned ? 
            long.low + long.high * 0x100000000 + (long.high >= 0 ? 0 : 0x100000000) :
            long.low + long.high * 0x100000000;
        
        // 检查是否在安全范围内
        if (value > MAX_SAFE_INTEGER || value < MIN_SAFE_INTEGER) {
            console.warn('长值超出安全整数范围，返回字符串');
            return value.toString();
        }
        
        return Number(value);
    }

    // 转换整数
    public static convertInteger(num: number): string {
        if (num === 0) return "零";
        
        const isNegative = num < 0;
        num = Math.abs(num);
        
        // 处理最大数字限制（1万亿）
        if (num > 999999999999) {
            throw new Error("数字过大，最大支持9999亿");
        }
        
        const units = ["", "十", "百", "千"];
        const bigUnits = ["", "万", "亿"];
        const digits = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
        
        // 特殊处理10-19
        if (num >= 10 && num <= 19) {
            return num === 10 ? "十" : `十${digits[num % 10]}`;
        }
        
        let result = "";
        let unitIndex = 0;
        let zeroFlag = false; // 标记是否需要添加"零"
        let allZero = true;   // 标记当前大单位是否全部为零
        
        while (num > 0) {
            const segment = num % 10000; // 每次处理四位
            num = Math.floor(num / 10000);
            
            let segmentResult = "";
            let temp = segment;
            let segmentZero = true; // 标记当前段是否全为零
            
            // 处理当前段（0-9999）
            for (let i = 0; i < 4; i++) {
                if (temp === 0) break;
                
                const digit = temp % 10;
                temp = Math.floor(temp / 10);
                
                if (digit === 0) {
                    if (!zeroFlag && segmentResult !== "") {
                        zeroFlag = true;
                    }
                } else {
                    segmentZero = false;
                    if (zeroFlag) {
                        segmentResult = "零" + segmentResult;
                        zeroFlag = false;
                    }
                    segmentResult = digits[digit] + units[i] + segmentResult;
                }
            }
            
            // 添加大单位（万、亿）
            if (!segmentZero) {
                allZero = false;
                result = segmentResult + bigUnits[unitIndex] + result;
            } else if (unitIndex > 0 && !allZero) {
                // 在万、亿单位处添加零（如10001 -> 一万零一）
                result = "零" + result;
                allZero = false;
            }
            
            unitIndex++;
        }
        
        // 处理负数
        if (isNegative) {
            result = "负" + result;
        }
        
        return result;
    }

}

function bezierTo(t: any, arg1: any[]) {
    throw new Error("Function not implemented.");
}
